package com.example.wechat_b.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wechat_b.activity.base.BaseActivity;
import com.example.wechat_b.utils.Custom;
import com.example.wechat_b.adapter.MainChatListAdapter;
import com.example.wechat_b.R;
import com.example.wechat_b.utils.SqliteDatabaseHelper;
import com.example.wechat_b.utils.AutoReplyUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {

    private ImageView ti_back;
    private TextView title;
    private ListView chat;
    private EditText editor;
    private Button btn_send;
    private List<Custom> customs;
    private MainChatListAdapter adapter;
    private SimpleDateFormat simpleDateFormat;
    private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH-mm");
    private Date currentTime;
    private SqliteDatabaseHelper sqliteDatabaseHelper;
    private SQLiteDatabase db;
    //    private ScrollView scrollView;
    private ImageButton ib_sound, ib_add, ib_expressions;
    private int type;
    private Boolean autoReplay = false;
    private SharedPreferences preferences;
    public static boolean CHANGE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_chat);

        sqliteDatabaseHelper = new SqliteDatabaseHelper(this, "withX", null, 2);
        db = sqliteDatabaseHelper.getWritableDatabase();
        preferences = getSharedPreferences("config", MODE_PRIVATE);
        autoReplay = preferences.getBoolean("autoReplay", false);
        customs = new ArrayList<>();
        init();
        initEvent();
//        chat.setFocusable(false);
    }

    @SuppressLint("CutPasteId")
    private void init() {
        Log.e("ChatActivity", "chatinit");
        ti_back = findViewById(R.id.chat_bar_img);
        title = findViewById(R.id.chat_bar_text);
        chat = findViewById(R.id.chat_list);
        editor = findViewById(R.id.send_edit);
        btn_send = findViewById(R.id.send_btn);
//        scrollView = findViewById(R.id.chat_scroll);
        ib_sound = findViewById(R.id.bottom_sound);
        ib_add = findViewById(R.id.bottom_add);
        Cursor cursor = db.query("jipeng", null, null, null, null, null, null);
        if (cursor.getCount() != 0) {
            while (cursor.moveToNext()) {
                Custom custom = new Custom();
                custom.TYPE = cursor.getInt(cursor.getColumnIndex("type"));
                custom.time = cursor.getString(cursor.getColumnIndex("time"));
                custom.toke = cursor.getString(cursor.getColumnIndex("token"));
                customs.add(custom);
            }
        }
        adapter = new MainChatListAdapter(ChatActivity.this, customs);
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        chat.setAdapter(adapter);

//        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//        getTimeExpend("2021/8/21 22:30","2021/8/21 22:33");
    }

    private void initEvent() {
        editor.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendMessage();
                }
                return false;
            }
        });
        if (ti_back.getVisibility() != View.VISIBLE) {
            ti_back.setVisibility(View.VISIBLE);
        }
        ti_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatActivity.this.finish();
            }
        });
        try {
            title.setText(getIntent().getStringExtra("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        chat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ChatActivity.this, "1", Toast.LENGTH_LONG).show();
            }
        });
        editor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(editor.getText().toString().trim())) {
                    ib_add.setVisibility(View.VISIBLE);
                    btn_send.setVisibility(View.GONE);
                } else {
                    ib_add.setVisibility(View.GONE);
                    btn_send.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editor.getText().toString().trim())) return;
                sendMessage();
            }
        });
//        btn_send.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if ("".contentEquals(editor.getText()) || editor.getText() == null) return;
//                CHANGE = true;
//                if (customs.isEmpty()) {
//                    currentTime = new Date();
//                    Custom custom = new Custom();
//                    custom.time = simpleDateFormat.format(currentTime);
//                    custom.TYPE = 0x03;
//                    customs.add(custom);
//                    ContentValues values = new ContentValues();
//                    values.put("type", custom.TYPE);
//                    values.put("time", custom.time);
//                    db.insert("jipeng", null, values);
//                }
//                String token = editor.getText().toString();
//                Custom custom = new Custom();
//                custom.TYPE = 0x02;
//                try {
//                    switch (Integer.parseInt(token.substring(token.length() - 1, token.length()))) {
//                        case 1:
//                            custom.TYPE = 0x01;
//                            custom.toke = token.substring(0, token.length() - 1);
//                            type = 1;
//                            break;
//                        case 2:
//                            custom.toke = token.substring(0, token.length() - 1);
//                            type = 2;
//                            break;
//                        case 3:
//                            custom.TYPE = 0x03;
//                            custom.toke = token.substring(0, token.length() - 1);
//                            type = 3;
//                            break;
//                    }
//                } catch (NumberFormatException e) {
//                    e.printStackTrace();
//                    custom.toke = token;
//                    custom.img = R.mipmap.mine;
//                    type = 2;
//                }
//                if (type == 2){
//                    autoSendMessage(token);
//                }
//                custom.time = simpleDateFormat.format(new Date());
//                customs.add(custom);
//                editor.setText("");
//                ContentValues values = new ContentValues();
//                values.put("type", custom.TYPE);
//                values.put("time", custom.time);
//                values.put("token", custom.toke);
//                db.insert("jipeng", null, values);
//                adapter.notifyDataSetChanged();
////                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//            }
//        });
    }

    private void sendMessage() {
        if (customs.isEmpty()) {
            currentTime = new Date();
            Custom custom = new Custom();
            custom.time = simpleDateFormat.format(currentTime);
            custom.TYPE = 0x03;
            customs.add(custom);
            ContentValues values = new ContentValues();
            values.put("type", custom.TYPE);
            values.put("time", custom.time);
            db.insert("jipeng", null, values);
        }
        Cursor cursor = db.query("jipeng", null, null, null, null, null, "id desc", "1");
        if (cursor.getCount() > 0) {
            cursor.moveToLast();
            String cDate = cursor.getString(cursor.getColumnIndex("time"));
            String nDate = simpleDateFormat.format(new Date());
            long low = getTimeExpend(cDate, nDate);
            if (low > 2) {
                currentTime = new Date();
                Custom custom = new Custom();
                custom.time = simpleDateFormat.format(currentTime);
                custom.TYPE = 0x03;
                customs.add(custom);
                ContentValues values = new ContentValues();
                values.put("type", custom.TYPE);
                values.put("time", custom.time);
                db.insert("jipeng", null, values);
            }
        }
        String token = editor.getText().toString();
        if (setAutoReplay(token)) {
            return;
        }
        Custom custom = new Custom();
        custom.TYPE = 0x02;
        try {
            final int i = Integer.parseInt(token.substring(token.length() - 1, token.length()));
            if (i == 1) {
                custom.TYPE = 0x01;
                custom.toke = token.substring(0, token.length() - 1);
                type = 1;
            } else if (i == 2) {
                custom.toke = token.substring(0, token.length() - 1);
                type = 2;
            } else if (i == 3) {
                custom.TYPE = 0x03;
                custom.toke = token.substring(0, token.length() - 1);
                type = 3;
            } else {
                custom.toke = token;
                type = 2;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            custom.toke = token;
            custom.img = R.mipmap.mine;
            type = 2;
        }

        if (autoReplay) {
            if (type == 2) {
                autoSendMessage(token);
            }
        }
        custom.time = simpleDateFormat.format(new Date());
        customs.add(custom);
        editor.setText("");
        ContentValues values = new ContentValues();
        values.put("type", custom.TYPE);
        values.put("time", custom.time);
        values.put("token", custom.toke);
        db.insert("jipeng", null, values);
        adapter.notifyDataSetChanged();
        btn_send.setVisibility(View.GONE);
        ib_add.setVisibility(View.VISIBLE);
    }

    private Boolean setAutoReplay(String token) {
        if ("闭嘴".equals(token)) {
            autoReplay = false;
            editor.setText("");
            preferences = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("autoReplay", autoReplay);
            editor.commit();
            Toast.makeText(ChatActivity.this, "Receiver Commend", Toast.LENGTH_LONG).show();
            return true;
        }
        if ("说话".equals(token)) {
            autoReplay = true;
            editor.setText("");
            preferences = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("autoReplay", autoReplay);
            editor.commit();
            Toast.makeText(ChatActivity.this, "Receiver Commend", Toast.LENGTH_LONG).show();
            return true;
        }
        if ("autoReplay==true".equals(token)) {
            autoReplay = true;
            editor.setText("");
            preferences = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("autoReplay", autoReplay);
            editor.commit();
            Toast.makeText(ChatActivity.this, "Receiver Commend", Toast.LENGTH_LONG).show();
            return true;
        }
        if ("autoReplay==false".equals(token)) {
            editor.setText("");
            autoReplay = false;
            preferences = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("autoReplay", autoReplay);
            editor.commit();
            Toast.makeText(ChatActivity.this, "Receiver Commend", Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }

    private long getTimeMillis(String strTime) {
        long returnMillis = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = null;
        try {
            d = sdf.parse(strTime);
            returnMillis = d.getTime();
        } catch (ParseException e) {
            Toast.makeText(ChatActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        return returnMillis;
    }

    private Long getTimeExpend(String startTime, String endTime) {
        //传入字串类型 2016/06/28 08:30
        long longStart = getTimeMillis(startTime); //获取开始时间毫秒数
        long longEnd = getTimeMillis(endTime);  //获取结束时间毫秒数
        long longExpend = longEnd - longStart;  //获取时间差

        long longHours = longExpend / (60 * 60 * 1000); //根据时间差来计算小时数
        long longMinutes = (longExpend - longHours * (60 * 60 * 1000)) / (60 * 1000);   //根据时间差来计算分钟数

//        Toast.makeText(ChatActivity.this, longHours + ":" + longMinutes, Toast.LENGTH_SHORT).show();
//        return longHours + ":" + longMinutes;
        return longMinutes + longHours * 60;
    }

    private String getHalfOfDay(){
        Calendar calendar = Calendar.getInstance();
        int now = calendar.get(Calendar.AM_PM);
        if (now == 1){
            return "上午";
        }else {
            return "下午";
        }
    }


    private void autoSendMessage(String res) {
        AutoReplyUtil autoReplyUtil = AutoReplyUtil.getInstance();
        String reply = autoReplyUtil.parseLanguage(res);
        if ("".equals(reply)) return;
        Message message = new Message();
        message.obj = reply;
        message.what = 0x1132;
        handler.sendMessageDelayed(message, 500);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x1132:
                    Custom custom = new Custom();
                    currentTime = new Date();
                    custom.time = simpleDateFormat.format(currentTime);
                    custom.TYPE = 0x01;
                    custom.toke = (String) msg.obj;
                    customs.add(custom);
                    ContentValues values = new ContentValues();
                    values.put("type", custom.TYPE);
                    values.put("time", custom.time);
                    values.put("token", custom.toke);
                    db.insert("jipeng", null, values);
                    adapter.notifyDataSetChanged();
//                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                    scrollView.scrollTo(0,0);
//                    scrollView.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                        }
//                    });
            }
        }
    };

    class SQLiteDataHolder {
        public int TYPE;
        public int img;
        public String toke;
        public String time;
    }
}